package com.kania.simpleemail.mailview;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.kania.simpleemail.R;
import com.kania.simpleemail.core.IMAP;
import com.kania.simpleemail.data.MailData;
import com.sun.mail.imap.IMAPFolder;

public class DetailViewActivity extends Activity {
	private SharedPreferences accountInfo;
	private final String STRING_ACCOUNT_PREFERENCE_NAME = "account_info";
	
	private TextView textFrom;
	private TextView textTo;
	private TextView textSubject;
	private TextView textDate;
	private TextView textContents;
	
	private String sID = "";
	private String sPassword = "";
	private String sHost = "imap.gmail.com";
	
	private long nReceivedUID = 0;
	
	private MailData mailData;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_view);
		
		accountInfo = this.getSharedPreferences(STRING_ACCOUNT_PREFERENCE_NAME, Activity.MODE_PRIVATE);
		sID = accountInfo.getString("exist_account", "");
		sPassword = accountInfo.getString("password", "");
		
		//debug
		this.setTitle(sID + " / " + sPassword);
		
		textFrom = (TextView)findViewById(R.id.detailviewTextFrom);
		textTo = (TextView)findViewById(R.id.detailviewTextTo);
		textSubject = (TextView)findViewById(R.id.detailviewTextSubject);
		textDate = (TextView)findViewById(R.id.detailviewTextDate);
		textContents = (TextView)findViewById(R.id.detailviewTextContents);
		
		Intent preIntent = getIntent();
		nReceivedUID = preIntent.getLongExtra("UID", 0);
		Log.d("KANIA_LOG_VIEW", "get UID = " + nReceivedUID);
		
		if (nReceivedUID != 0) {
			new MailReadTask().execute();
		}
	}
	
	class MailReadTask extends AsyncTask<Void, Void, Boolean> {
		IMAP loginSession;
		boolean bSuccessAccess = false;
		int nMsgCount = 0;
		Message mail = null;
		Folder folder;
		
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				//세션을 만들고 접근을 시도한 다음
//				loginSession = new IMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [start]
				loginSession = IMAP.getInstance();
				loginSession.initIMAP(sHost, sID, sPassword);
				//[130828] changed by singleton parttern using [end]
				loginSession.open();
				
				//이상없이 접근이 성공하였다면 메일을 UID를 통해 불러온다
				if (loginSession.getFolder().isOpen() == true) {
					Log.d("KANIA_LOG_VIEW", "open Success!");
					folder = loginSession.getFolder();
					bSuccessAccess = true;
					
					mail = ((IMAPFolder)folder).getMessageByUID(nReceivedUID);
					Log.d("KANIA_LOG_VIEW", "read UID = " + nReceivedUID);
				}
				
				if (mail != null) {
					String from = new String(mail.getFrom()[0].toString().getBytes(), "UTF-8");
					String subject = mail.getSubject();
					Calendar date = Calendar.getInstance();
					date.setTime(mail.getSentDate());
//					mailData = new MailData(from, date, subject);
//					mailData.setUID(nReceivedUID);
//					try {
//						mailData.setContents(mail.getContent().toString());
//					} catch (IOException e) {
//						Log.e("KANIA_LOG_VIEW", "IOException");
//						e.printStackTrace();
//					}
					
					
				}
			} catch (NoSuchProviderException e) {
				Log.e("KANIA_LOG_VIEW", "NoSuchProviderException");
				bSuccessAccess = false;
			} catch (MessagingException e) {
				Log.e("KANIA_LOG_VIEW", "MessagingException");
				bSuccessAccess = false;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				Log.e("KANIA_LOG_VIEW", "UnsupportedEncodingException");
				bSuccessAccess = false;
			} finally {
				endSession();
			}
			return bSuccessAccess;
		}
		
		public void endSession(){
			try {
				loginSession.close();
				
			} catch (MessagingException e) {
				Log.e("KANIA_LOG_VIEW", "MessagingException in EndSession");
				bSuccessAccess = false;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			textFrom.setText(mailData.getFromData());
			textTo.setText(sID);
			textSubject.setText(mailData.getMailSubject());
			textDate.setText(mailData.getMailDate());
			textContents.setText(mailData.getContents());
			super.onPostExecute(result);
		}
		
	}

}
